package com.juyu.miliao.api.service;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.juyu.miliao.api.dao.mysql.AreaDao;
import com.juyu.miliao.api.domain.AreaInfo;
import com.juyu.miliao.api.domain.vo.AreaVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.KeyBoundCursor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author xuanqicheng
 * @create 2019-08-13:15
 */
@Service
public class AreaService {

    @Autowired
    private AreaDao areaDao;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public List<String> selectProvinceList() {
        return areaDao.selectProvinceList();
    }

    public List<String> selectCityByProvince(String province) {
        if(province.equals("北京市")||province.startsWith("天津市")
                ||province.startsWith("上海市")||province.startsWith("重庆市")){
            List<String> cityList = new ArrayList<>();
            cityList.add(province);
            return cityList;
        }else{
            return areaDao.selectCityByProvince(province);
        }
    }

    public List<AreaVo> selectAreaList() throws IOException {
        String areaKey = "MAKE_FRIENDS_AREA_LIST";
        String target = stringRedisTemplate.opsForValue().get(areaKey);
        if(StringUtils.isNotBlank(target)){
            JavaType  javaType = objectMapper.getTypeFactory().constructParametricType(
                    List.class, AreaVo.class);
            List<AreaVo> areaVoList = objectMapper.readValue(target,javaType);
            return areaVoList;
        }else {
            //查询省
            List<AreaInfo> areaInfoList = areaDao.selectProvinceInfoList();
            List<AreaVo> resultList = new ArrayList<>();
            for (AreaInfo areaInfo : areaInfoList) {
                AreaVo areaVo = new AreaVo();
                areaVo.setName(areaInfo.getAreaName());
                List<String> cityList = areaDao.selectCityByProvinceId(areaInfo.getAreaId());
                if (cityList.size() > 0) {
                    areaVo.setCity(cityList);
                }
                resultList.add(areaVo);
            }
            if(resultList.size()>0){
               stringRedisTemplate.opsForValue().set(areaKey,objectMapper.writeValueAsString(resultList),30, TimeUnit.MINUTES);
            }
            return resultList;
        }
    }
}
